<?php
/**
* funsiotn cloned from sphinx api, but modified to soundshare requirements
* @name EscapeString
* @abstract
*/

 function sphinx_escape( $string )
 {
	return preg_replace( "#[\\\|!@()~\"^$=\-]#u", ' ', $string );
 }

function normalizeUrl($url, $ns, $has_ns = false)
{
	if ($has_ns) $urls = explode(':', $url, 2);
       	$res = '';
       	if ($urls[1]) {
       	        $res = $urls[0].":";
       	        $temp = $urls[1];
       	} else {
		$temp = $url;
	}

	switch ($ns)
	{	
		case NS_ARTIST:
			$res .= mb_ucfirst(normalize($temp));
			break;
		case NS_RELEASE:
		case NS_SONG:
			$urls = explode('/', $temp, 2);
			$res .= mb_ucfirst(normalize($urls[0])).'/'.mb_ucfirst(normalize($urls[1]));
			break;
		default:
			$res = $url;
			break;
	}
	return $res;
}

function mb_ucfirst($str) {
	return mb_convert_case(mb_substr($str, 0, 1), MB_CASE_UPPER).mb_substr($str, 1);
}

function mb_string2array ($str) {
    if (empty($str)) return array();
    $len = mb_strlen($str);
    $array = array();
    for ($i = 0; $i < $len; $i++) {
        $array[] = mb_substr($str, $i, 1);
    }
    return $array;
}

function mb_levenshtein($ss, $st) {
	$m = mb_strlen($ss);
	$n = mb_strlen($st);
	
	$s = mb_string2array($ss);
	$t = mb_string2array($st);
 
	for($i=0;$i<=$m;$i++) $d[$i][0] = $i;
	for($j=0;$j<=$n;$j++) $d[0][$j] = $j;
 
	for($i=1;$i<=$m;$i++) {
		for($j=1;$j<=$n;$j++) {
			$c = ($s[$i-1] == $t[$j-1])?0:1;
			$d[$i][$j] = min($d[$i-1][$j]+1,$d[$i][$j-1]+1,$d[$i-1][$j-1]+$c);
		}
	}
 
	return $d[$m][$n];
}

function mb_trim ($str, $rem = ' ') {
    if (empty($str)) return false;
    // convert to array
    $arr = mb_string2array($str);
    $len = count($arr);
    // left side
    for ($i = 0; $i < $len; $i++) {
        if ($arr[$i] === $rem) $arr[$i] = '';
        else break;
        }
    // right side
    for ($i = $len-1; $i >= 0; $i--) {
        if ($arr[$i] === $rem) $arr[$i] = '';
        else break;
    }
    // convert to string
    return implode('', $arr);
}

function normalize($text, $spaces=false)
{
       //ini_set('display_errors', 1);
       //$pear_path = 'C:\wamp\bin\php\php5.2.6\PEAR';
       set_include_path(  $pear_path  . PATH_SEPARATOR . get_include_path() );

       //erro_reporting(E_ALL);
       //require_once 'PEAR.php';
       require_once('I18N/UnicodeNormalizer.php');
       //PEAR::setErrorHandling(PEAR_ERROR_DIE);

       //let's normalize
       if (class_exists("I18N_UnicodeNormalizer", $autoload = false)){

        	$ntext = I18N_UnicodeNormalizer::toNFKD( $text );
		if ($spaces)
			$result = preg_replace("/[^\pL\pN]/u", " ", $ntext);
		else
			$result = preg_replace("/[^\pL\pN]/u", "", $ntext);
               return mb_convert_case($result, MB_CASE_LOWER);
       } else {
               return die('the pear package I18N_UnicodeNormalizer is not installed, or you have a problem with the pear path');
       }
    }

function TotalFilesNum()
       {

        $dbr = wfGetDB( DB_SLAVE );
        $sql = "SELECT SQL_CACHE COUNT(IdFile) as files FROM ss_file";
        $resql = $dbr->query( $sql );


        $row = $dbr->fetchObject( $resql );

        $totalfiles = $row->files;
        
        //return '<div class="index_files_claim"><small>indexing '.$totalfiles.' p2p links today</small></div>';
        return $totalfiles;
        $dbr->freeResult( $resql );
       }




function ByteSize($bytes)
   {
   $size = $bytes / 1024;
   if($size < 1024)
       {
       $size = number_format($size, 2);
       $size .= ' KB';
       }
   else
       {
       if($size / 1024 < 1024)
           {
           $size = number_format($size / 1024, 2);
           $size .= ' MB';
           }
       else if ($size / 1024 / 1024 < 1024)
           {
           $size = number_format($size / 1024 / 1024, 2);
           $size .= ' GB';
           }
       }
   return  $size;
   }

function convertS2String($time) {
         return sprintf("%2d:%02d", floor($time/60), $time%60);
}

function ss_nameize($str,$a_char = array("'","-"," ")){
   //$str contains the complete raw name string
   //$a_char is an array containing the characters we use as separators for capitalization. If you don't pass anything, there are three in there as default.

       if(!empty($string)){
       $string = strtolower($str);
       }

       $string = strtolower($str);
   foreach ($a_char as $temp){
       $pos = strpos($string,$temp);
       if ($pos){
           //we are in the loop because we found one of the special characters in the array, so lets split it up into chunks and capitalize each one.
           $mend = '';
           $a_split = explode($temp,$string);
           foreach ($a_split as $temp2){
               //capitalize each portion of the string which was separated at a special character
               $mend .= ucfirst($temp2).$temp;
               }
           $string = substr($mend,0,-1);
           }
       }
   return ucfirst($string);
   }

function ss_getArticleRawText($url)
{
	$title = SoundshareTitle::newFromDBKey($url);
	$article = new Article($title);
	if ($article==null)
		return null;
	else
		return $article->getRawText();
}

function  ss_checkSearchFlags($param){
        global $wgRequest,$wgOut;
        if ($wgRequest->getText( $param ) == 'on') {
        	$out ='value="on" checked="true"';
        } else {
		$out = '';
        }
	return $out;
}

function truncateString($str, $max, $rep = '...') {
 if(mb_strlen($str) > $max) {
   return mb_substr($str, 0, $max).$rep;
 } else {
   return $str;
 }
}

function crcGenre($genre){
	return crc32(normalize($genre));
}

function createURL($pattern, $data)
{
	for ($i=0; $i<count($data); $i++)
		$data[$i] = mb_ereg_replace('/', ' ', $data[$i]);
	return vsprintf($pattern, $data);
}

function coalesce() {
  $args = func_get_args();
  foreach ($args as $arg) {
    if (!is_null($arg)) {
      return $arg;
    }
  }
  return NULL;
}


/**
* Truncates text.
*
* Cuts a string to the length of $length and replaces the last characters
* with the ending if the text is longer than length.
*
* @param string  $text String to truncate.
* @param integer $length Length of returned string, including ellipsis.
* @param mixed $ending If string, will be used as Ending and appended to the trimmed string. Can also be an associative array that can contain the last three params of this method.
* @param boolean $considerHtml If true, HTML tags would be handled correctly
* @return string Trimmed string.
*/
function truncate($text, $length = 100, $ending = '...', $considerHtml = false) {
    if (is_array($ending)) {
        extract($ending);
    }
    if ($considerHtml) {
        if (mb_strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
            return $text;
        }
        $totalLength = mb_strlen($ending);
        $openTags = array();
        $truncate = '';
        preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
        foreach ($tags as $tag) {
            if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) {
                if (preg_match('/<[\w]+[^>]*>/s', $tag[0])) {
                    array_unshift($openTags, $tag[2]);
                } else if (preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag)) {
                    $pos = array_search($closeTag[1], $openTags);
                    if ($pos !== false) {
                        array_splice($openTags, $pos, 1);
                    }
                }
            }
            $truncate .= $tag[1];
 
            $contentLength = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $tag[3]));
            if ($contentLength + $totalLength > $length) {
                $left = $length - $totalLength;
                $entitiesLength = 0;
                if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $tag[3], $entities, PREG_OFFSET_CAPTURE)) {
                    foreach ($entities[0] as $entity) {
                        if ($entity[1] + 1 - $entitiesLength <= $left) {
                            $left--;
                            $entitiesLength += mb_strlen($entity[0]);
                        } else {
                            break;
                        }
                    }
                }
		switch ($openTags[0])
		{
			case 'a':
				$truncate .= "$tag[3]</a>";
				array_shift($openTags);
				break;
			case 'p':
				$dot = mb_strrpos($tag[3], ".");
				if (isset($dot) && abs($totalLength+$dot-$length)<40)
				{
					$truncate .= mb_substr($tag[3], 0, $dot+1);
					$ending = '';
					break;
				}
				// if doesn't have a dot near limit, doesn't break and truncate word
			default:
	                	$truncate .= mb_substr($tag[3], 0 , $left + $entitiesLength);
				break;
                }
		break;
            } else {
                $truncate .= $tag[3];
                $totalLength += $contentLength;
            }
            if ($totalLength >= $length) {
                break;
            }
        }
 
    } else {
        if (mb_strlen($text) <= $length) {
            return $text;
        } else {
            $truncate = mb_substr($text, 0, $length - strlen($ending));
        }
    }

    $truncate .= $ending;
 
    if ($considerHtml) {
        foreach ($openTags as $tag) {
            $truncate .= "</$tag>";
        }
    }
 
    return $truncate;
}
